import { GetAllCollegeQuery, CollegeEntity } from "@/queries/college";
import { useQuery } from "@apollo/client";
import { Key, useCallback, useEffect, useMemo, useState } from "react";
import { Tree } from "antd";
import type { TreeProps } from "antd/es/tree";

type SelectClassesItemProps = {
  onChange?: (value: string) => void;
  value?: string;
};
const SelectClassesItem = ({ onChange, value }: SelectClassesItemProps) => {
  const { data, refetch } = useQuery(GetAllCollegeQuery);
  useEffect(() => {
    if (!!data) refetch();
  }, []);
  const colleges: CollegeEntity[] = useMemo(
    () => data?.getAllCollege || [],
    [data]
  );
  const treeData = useMemo(
    () =>
      colleges.map((college) => {
        return {
          key: `${college.id}`,
          title: college.name,
          children: college.Department.map((dept) => ({
            key: `${college.id}_${dept.id}`,
            title: dept.name,
            children: dept.Science.map((science) => ({
              key: `${college.id}_${dept.id}_${science.id}`,
              title: science.name,
              children: science.Classes.map((classes) => ({
                key: `${college.id}_${dept.id}_${science.id}_${classes.id}`,
                title: classes.name,
              })),
            })),
          })),
        };
      }),
    [colleges]
  );
  const [selectedKeys, setSelectedKeys] = useState<
    | Key[]
    | {
        checked: Key[];
        halfChecked: Key[];
      }
  >([]);
  useEffect(() => {
    if (!value) return;
    setSelectedKeys(JSON.parse(value));
  }, [value]);
  const onSelectionChange: TreeProps["onCheck"] = useCallback((value) => {
    setSelectedKeys(value);
    if (!!onChange) {
      if (!!value) {
        onChange(JSON.stringify(value));
      } else {
        onChange("[]");
      }
    }
  }, []);
  return (
    <div>
      <Tree
        treeData={treeData}
        checkable
        checkedKeys={selectedKeys}
        onCheck={onSelectionChange}
        className="w-full m-0 p-0"
      />
    </div>
  );
};
export default SelectClassesItem;
